﻿using System;
using System.Collections;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;
using System.Reflection;

namespace Vav.Data.Utils
{
   public static class EnumHelper
    {
    
        /// <summary>
        /// 获取枚举类型的Description
        /// </summary>
        /// <typeparam name="TEnum"></typeparam>
        /// <param name="value"></param>
        /// <returns></returns>
        public static string ToEnumDescription<TEnum>(this TEnum value) where TEnum: struct
        {
            Type type = typeof(TEnum);
            if (!type.IsEnum)
            {
                throw new ArgumentException("TEnum requires a Enum", "TEnum");
            }
            var field = type.GetField(Enum.GetName(type, value));
            return field?.GetCustomAttribute<DescriptionAttribute>()?.Description;
        }

        public static TEnum ToEnumFromDescription<TEnum>(this string value) where TEnum: struct
        {
            return (TEnum)typeof(TEnum)
                .GetFields()
                .Select(field => new { Field = field, Description = field.GetCustomAttribute<DescriptionAttribute>() })
                .First(info => info.Description.Description == value)
                .Field.GetValue(null);
        }

        public static string ToEnumDescription<TEnum>(this int value) where TEnum : struct
        {
            return ((TEnum)(dynamic)value).ToEnumDescription();
        }
    }
}
